package com.example.fireassistant_server.service.impl;

import com.example.fireassistant_server.dto.company.CompanyCreateRequest;
import com.example.fireassistant_server.dto.company.CompanyDto;
import com.example.fireassistant_server.dto.company.CompanySearchFilter;
import com.example.fireassistant_server.dto.company.CompanyUpdateRequest;
import com.example.fireassistant_server.entity.Circle;
import com.example.fireassistant_server.entity.Company;
import com.example.fireassistant_server.entity.File;
import com.example.fireassistant_server.entity.User;
import com.example.fireassistant_server.exception.BizException;
import com.example.fireassistant_server.exception.ExceptionType;
import com.example.fireassistant_server.mapper.CompanyMapper;
import com.example.fireassistant_server.repository.CompanyRepository;
import com.example.fireassistant_server.repository.UserRepository;
import com.example.fireassistant_server.repository.WechatUserRepository;
import com.example.fireassistant_server.repository.spec.*;
import com.example.fireassistant_server.service.CompanyService;
import com.example.fireassistant_server.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class CompanyServiceImpl implements CompanyService {

    CompanyRepository companyRepository;

    CompanyMapper companyMapper;

    UserRepository userRepository;

    WechatUserRepository wechatUserRepository;

    private FileService fileService;
    @Override
    public CompanyDto create(CompanyCreateRequest companyCreateRequest) {
        Company company = companyMapper.createEntity(companyCreateRequest);
        return companyMapper.toDto(companyRepository.save(company));
    }

    @Override
    public Company get(String id) {
        Optional<Company> company = companyRepository.findById(id);
        if (!company.isPresent()) {
            throw new BizException(ExceptionType.COMPANY_NOT_FOUND);
        }
        return company.get();
    }

    //按条件搜索单位名称
    @Override
    public Page<CompanyDto> search(CompanySearchFilter companySearchFilter) {
        CompanySpecification specs = new CompanySpecification();
        if (companySearchFilter.getProvince() != null && !Objects.equals(companySearchFilter.getProvince(), "")) {
            specs.add(new SearchCriteria("province",companySearchFilter.getProvince(),SearchOperation.MATCH));
        }
        if (companySearchFilter.getCityName() != null && !Objects.equals(companySearchFilter.getCityName(), "")) {
            specs.add(new SearchCriteria("cityName",companySearchFilter.getCityName(),SearchOperation.MATCH));
        }

        return companyRepository.findAll(specs, companySearchFilter.toPageable()).map(companyMapper::toDto);
    }



    //TODO
    @Override
    @Transactional
    public void delete(String id) {
        Optional<Company> company = companyRepository.findById(id);
        if (!company.isPresent()) {
            throw new BizException(ExceptionType.COMPANY_NOT_FOUND);
        }
        List<User> userList = userRepository.findByCompany_Id(id);

        if (!userList.isEmpty()){
            userList.forEach(user->{
                // 删除微信用户
                wechatUserRepository.deleteByUserId(user.getId());
            });

            //删除从表所有用户
            userRepository.deleteByCompany_Id(id);
        }

        //删除主表
        companyRepository.deleteById(id);

        // 先删除对应的file
        List<File> files=company.get().getFiles();
        if (!files.isEmpty()){
            files.forEach(item->{
                fileService.delete("company",item.getId());
            });
        }

    }

    @Override
    public CompanyDto update(String id, CompanyUpdateRequest companyUpdateRequest) {
        Optional<Company> company = companyRepository.findById(id);

        if (!company.isPresent()) {
            throw new BizException(ExceptionType.CIRCLE_NOT_FOUND);
        }

        if (companyUpdateRequest.getLatitude()!= null){
            company.get().setLatitude(companyUpdateRequest.getLatitude());
        }

        if (companyUpdateRequest.getLongitude()!= null){
            company.get().setLongitude(companyUpdateRequest.getLongitude());
        }

        if (companyUpdateRequest.getRadius()!=0.0){
            company.get().setRadius(companyUpdateRequest.getRadius());
        }

        if (companyUpdateRequest.getDescription()!= null){
            company.get().setDescription(companyUpdateRequest.getDescription());
        }

        if (companyUpdateRequest.getCompanyName()!= null){
            company.get().setCompanyName(companyUpdateRequest.getCompanyName());
        }

        companyRepository.flush();
        return companyMapper.toDto(companyRepository.save(company.get()));
    }


    @Autowired
    public void setCompanyRepository(CompanyRepository companyRepository) {
        this.companyRepository = companyRepository;
    }

    @Autowired
    public void setCompanyMapper(CompanyMapper companyMapper) {
        this.companyMapper = companyMapper;
    }

    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Autowired
    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }

    @Autowired
    public void setWechatUserRepository(WechatUserRepository wechatUserRepository) {
        this.wechatUserRepository = wechatUserRepository;
    }
}
